//
// Created by yangchao on 2022/4/26.
// 22. 括号生成: https://leetcode-cn.com/problems/generate-parentheses/
//
#include <vector>
#include <string>
using namespace std;
/*
 * [" ((()))"," (()())"," (())()"," ()(())"," ()()()"]
   ["((()))","(()())","(())()","()(())","()()()"]
 * */
class GenerateParenthesis{
public:
    vector<string> generateParenthesis(int n) {
        if (n == 0) return {};
        vector<string> res;
        string path;
        backtrack(n,n,res,path);
        return res;
    }

    void backtrack(int left, int right, vector<string>& res,string& path) {
        if (left == 0 && right == 0) {
            res.push_back(path);
            return;
        }
        if (left > right) return;
        if (left > 0) {
            path.push_back('(');
            backtrack(left-1,right,res,path);
            path.pop_back();
        }
        if (right > 0) {
            path.push_back(')');
            backtrack(left,right-1,res,path);
            path.pop_back();
        }
    }
};
